package com.itheima.service.db.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.domain.db.AnalysisByDay;
import com.itheima.domain.db.SummaryData;
import com.itheima.domain.db.SummaryDataReturn;
import com.itheima.mapper.AnalysisByDayMapper;
import com.itheima.mapper.LogMapper;
import com.itheima.service.db.AnalysisByDayService;
import com.itheima.util.ComputeUtil;
import com.itheima.vo.AnalysisSummaryVo;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Query;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@DubboService
public class AnalysisByDayServiceImpl implements AnalysisByDayService {

    @Autowired
    LogMapper logMapper;

    @Autowired
    AnalysisByDayMapper analysisByDayMapper;

    @Override
    public void saveOrUpdate() {
        //0.准备昨日和今日的日期字符串
        String today = DateUtil.offsetDay(new Date(), 0).toDateStr();
        String yesterday = DateUtil.offsetDay(new Date(), -1).toDateStr();

        //1.通过日期查询统计表中的数据
        LambdaQueryWrapper<AnalysisByDay> qw = new LambdaQueryWrapper<>();
        qw.eq(AnalysisByDay::getRecordDate, today);
        AnalysisByDay analysisByDay = analysisByDayMapper.selectOne(qw);

        //2.判断今日数据是否存在
        if (analysisByDay != null) {
            //2.1 若存在则更新
            analysisByDay.setNumRegistered(logMapper.findRegisterOrLoginCount(today, "0102"));
            analysisByDay.setNumActive(logMapper.findActiveCount(today));
            analysisByDay.setNumLogin(logMapper.findRegisterOrLoginCount(today, "0101"));
            analysisByDay.setNumRetention1d(logMapper.findRetention1d(today, yesterday));

            analysisByDayMapper.updateById(analysisByDay);
        } else {
            //2.2 若不存在则保存
            analysisByDay = new AnalysisByDay();

            analysisByDay.setRecordDate(new Date());
            analysisByDay.setNumRegistered(logMapper.findRegisterOrLoginCount(today, "0102"));
            analysisByDay.setNumActive(logMapper.findActiveCount(today));
            analysisByDay.setNumLogin(logMapper.findRegisterOrLoginCount(today, "0101"));
            analysisByDay.setNumRetention1d(logMapper.findRetention1d(today, yesterday));

            analysisByDayMapper.insert(analysisByDay);
        }
    }

    // 展示统计数据
    @Override
    public AnalysisSummaryVo findSummary() {
        //1.准备基础数据
        Date day = new Date();
        String today = DateUtil.offsetDay(day, 0).toDateStr();
        String yesterday = DateUtil.offsetDay(day, -1).toDateStr();
        String passWeek = DateUtil.offsetDay(day, -7).toDateStr();
        String passMonth = DateUtil.offsetDay(day, -30).toDateStr();

        //准备今天的所有数据
        AnalysisByDay todayData = analysisByDayMapper.findByRecordDate(today);
        //准备昨天的所有数据
        AnalysisByDay yesterdayData = analysisByDayMapper.findByRecordDate(yesterday);

        //2.创建vo
        AnalysisSummaryVo vo = new AnalysisSummaryVo();

        //3.设置9个字段
        //累计用户数
        vo.setCumulativeUsers(analysisByDayMapper.findUserTotalCount());
        //过去30天活跃用户数
        vo.setActivePassMonth(analysisByDayMapper.findActiveUserCountInPeriod(passMonth, yesterday));
        //过去7天活跃用户
        vo.setActivePassWeek(analysisByDayMapper.findActiveUserCountInPeriod(passWeek, yesterday));
        //今日新增用户数量
        vo.setNewUsersToday(todayData.getNumRegistered().longValue());
        //今日新增用户涨跌率，单位百分数，正数为涨，负数为跌   BigDecimal : 商业数字格式
        vo.setNewUsersTodayRate(ComputeUtil.computeRate(todayData.getNumRegistered(), yesterdayData.getNumRegistered()));
        //今日登录次数
        vo.setLoginTimesToday(todayData.getNumLogin().longValue());
        //今日登录次数涨跌率，单位百分数，正数为涨，负数为跌
        vo.setLoginTimesTodayRate(ComputeUtil.computeRate(todayData.getNumLogin(), yesterdayData.getNumLogin()));
        //今日活跃用户数量
        vo.setActiveUsersToday(todayData.getNumActive().longValue());
        //今日活跃用户涨跌率，单位百分数，正数为涨，负数为跌
        vo.setActiveUsersTodayRate(ComputeUtil.computeRate(todayData.getNumActive(), yesterdayData.getNumActive()));

        //4.返回vo
        return vo;
    }


    //查询需要的数据
    @Override
    public SummaryData findSummaryData(Long startDate, Long endDate, String type) {

        //查询今年的数据
        //开始时间
        String start =  DateUtil.offsetDay(new Date(Long.valueOf(startDate)),0).toDateStr();
        //结束时间
        String end =  DateUtil.offsetDay(new Date(Long.valueOf(endDate)),0).toDateStr();
        //根据时间获取每日数据集合
        List<AnalysisByDay> analysisByDays = analysisByDayMapper.selectByTime(start, end);
        List<SummaryDataReturn> thisYear = new ArrayList<>();

        //判断集合是否为空
        if (CollUtil.isNotEmpty(analysisByDays)) {
            analysisByDays.forEach(analysisByDay -> {
                if (analysisByDay != null) {
                    switch (type) {
                        case "101": {
                            SummaryDataReturn summaryDataReturn = new SummaryDataReturn();
                            //获取当前日期
                            summaryDataReturn.setTitle(DateUtil.formatDate(analysisByDay.getRecordDate()));
                            //获取当前日期的注册数
                            summaryDataReturn.setAmount(analysisByDay.getNumRegistered());
                            thisYear.add(summaryDataReturn);
                        }
                        case "102": {
                            SummaryDataReturn summaryDataReturn = new SummaryDataReturn();
                            summaryDataReturn.setTitle(DateUtil.formatDate(analysisByDay.getRecordDate()));
                            summaryDataReturn.setAmount(analysisByDay.getNumActive());
                            thisYear.add(summaryDataReturn);
                        }
                        case "103": {
                            SummaryDataReturn summaryDataReturn = new SummaryDataReturn();
                            summaryDataReturn.setTitle(DateUtil.formatDate(analysisByDay.getRecordDate()));
                            /*String yesterday = DateUtil.offsetDay( analysisByDay.getRecordDate(), -1).toDateStr();
                            AnalysisByDay analysisByLastDay = analysisByDayMapper.findByRecordDate(yesterday);
                            ComputeUtil.computeRate(analysisByDay.getNumRetention1d(),analysisByLastDay.getNumRegistered());
                            summaryDataReturn.setAmount(analysisByDay.getNumRetention1d()/(analysisByLastDay.getNumRegistered()));*/
                            summaryDataReturn.setAmount(analysisByDay.getNumRetention1d());
                            thisYear.add(summaryDataReturn);
                        }
                    }
                }
            });
        }

        //查询去年的数据
        //1.准备基础数据
        String lastStart = DateUtil.offset(new Date(startDate), DateField.YEAR, -1).toDateStr();
        String lastEnd = DateUtil.offset(new Date(endDate), DateField.YEAR, -1).toDateStr();
        List<AnalysisByDay> analysisByDayList = analysisByDayMapper.selectByTime(lastStart, lastEnd);
        List<SummaryDataReturn> lastYear=new ArrayList<>();
        if (CollUtil.isNotEmpty(analysisByDayList)){
            analysisByDayList.forEach(analysisByDay -> {

                if (analysisByDay!=null){
                    switch (type){
                        case "101":{
                            SummaryDataReturn summaryDataReturn=new SummaryDataReturn();
                            summaryDataReturn.setTitle(DateUtil.formatDate(analysisByDay.getRecordDate()));
                            summaryDataReturn.setAmount(analysisByDay.getNumRegistered());
                            lastYear.add(summaryDataReturn);
                        }
                        case "102":{
                            SummaryDataReturn summaryDataReturn=new SummaryDataReturn();
                            summaryDataReturn.setTitle(DateUtil.formatDate(analysisByDay.getRecordDate()));
                            summaryDataReturn.setAmount(analysisByDay.getNumActive());
                            lastYear.add(summaryDataReturn);
                        }
                        case "103":{
                            SummaryDataReturn summaryDataReturn=new SummaryDataReturn();
                            summaryDataReturn.setTitle(DateUtil.formatDate(analysisByDay.getRecordDate()));
                            summaryDataReturn.setAmount(analysisByDay.getNumRetention1d());
                            lastYear.add(summaryDataReturn);
                        }
                    }
                }
            });
        }

        SummaryData summaryData = new SummaryData();
        summaryData.setThisYear(thisYear);
        summaryData.setLastYear(lastYear);
        return summaryData;
    }
}
